package com.bilin.coin.activity;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.utils.TextUtils;
import com.bilin.coin.ApiConstant;
import com.bilin.coin.BuildConfig;
import com.bilin.coin.MainActivity;
import com.bilin.coin.R;
import com.bilin.coin.bean.AccountBean;
import com.bilin.coin.bean.CommonSuccessEvent;
import com.bilin.coin.bean.LoginBean;
import com.bilin.coin.common.base.BaseAppCompatActivity;
import com.bilin.coin.network.RequestUtils;
import com.bilin.coin.network.RetrofitConfig;
import com.bilin.coin.network.callback.CommonCallBack;
import com.bilin.coin.tools.Geter;
import com.bilin.coin.utils.DeviceIdUtil;
import com.bilin.coin.utils.DialogUtils;
import com.bilin.coin.utils.GsonUtil;
import com.bilin.coin.utils.MobilePhoneDeviceInfo;
import com.bilin.coin.utils.SharedPreferencesUtils;
import com.bilin.coin.utils.TimerUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = "/auction/UnbindActivity")
public class UnbindActivity extends BaseAppCompatActivity {

    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_pass)
    EditText et_pass;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.rl_send)
    RelativeLayout rl_send;
    @BindView(R.id.v_send)
    View v_send;
    @BindView(R.id.bt_send)
    TextView bt_send;
    @BindView(R.id.tv_bind_phone)
    TextView tv_bind_phone;
    @BindView(R.id.tv_device_id)
    TextView tv_device_id;
    @BindView(R.id.tv_remain_time)
    TextView tv_remain_time;


    @Override
    protected void initView() {

        setTitle("设备解绑");
        tv_device_id.setText(""+DeviceIdUtil.getDeviceId(this));
        getData();
    }

    private void getData() {

        new Geter(this, true, true) {
            @Override
            protected String fillUrl() {
                return "/api/bl-bind/getAccountFromDeviceCode";
            }

            @Override
            protected Map<String, String> fillParams() {
                HashMap hashMap = new HashMap();
                hashMap.put("deviceCode", DeviceIdUtil.getDeviceId(UnbindActivity.this));
                return hashMap;
            }

            @Override
            protected void disposeSuccess(String dataJson) {
                super.disposeSuccess(dataJson);
                AccountBean accountBean = GsonUtil.GsonToBean(dataJson, AccountBean.class);
                if (TextUtils.isEmpty(accountBean.getAccount())) {
                    tv_bind_phone.setText("当前设备未绑定手机号");
                } else {
                    tv_bind_phone.setText("当前设备绑定手机号："+accountBean.getAccount());
                }
                tv_remain_time.setText("剩余解绑次数："+accountBean.getTimes());
            }
        };
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_unbind;
    }

    @Override
    public boolean isShowToolBar() {
        return true;
    }


    @OnClick({ R.id.tv_forget_pass,R.id.bt_send,R.id.bt_confirm,
            R.id.tv_create,R.id.tv_protocol_user,R.id.tv_device_id,
            R.id.tv_protocol_private,R.id.tv_unbind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_device_id:
                copeClipSuccess(tv_device_id);
                break;
            case R.id.tv_unbind:
                baseStartActivity("/confirm/confirm/FindBackActivity");
                break;
            //找回密码
            case R.id.tv_forget_pass:
                baseStartActivity("/confirm/confirm/FindBackActivity");
                break;
            //登录
            case R.id.bt_confirm:
                loginWithCode();
                break;
            case R.id.tv_create:
                baseStartActivity("/auction/RegisterActivity");
                break;
            case R.id.bt_send:
                sendRegCode();
                break;
            case R.id.tv_protocol_user:
                jumpProtocol(RetrofitConfig.newsUrl+"0", "用户协议");
                break;
            case R.id.tv_protocol_private:
                jumpProtocol(ApiConstant.PRIVACY_PROTOCOL, "隐私协议");
                break;
        }
    }

    private void loginWithCode() {
        String code = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            showToast(getResources().getString(R.string.sms_code_empty));
            return;
        }
        String pwd = et_pass.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            showToast("密码不能为空");
            return;
        }
        String account = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            showToast("账号不能为空");
            return;
        }
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .post()
                .url("/api/bl-bind/unBindDevice")
                .addParams("code", code)
                .addParams("account", account)
                .addParams("deviceCode", DeviceIdUtil.getDeviceId(UnbindActivity.this))
                .addParams("pwd", pwd)
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {

                    @Override
                    protected void onError(String errorMsg) {
                        DialogUtils.dismissDialogLoading();
                        showToast(errorMsg);
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        showToast("操作成功");
                        DialogUtils.dismissDialogLoading();
                        finish();
                    }

                    @Override
                    protected void onCallBackError(Throwable e) {
                        showMsg(e);
                        DialogUtils.dismissDialogLoading();
                    }
                });

    }

    private void saveUserInfo(LoginBean loginBean) {
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.CSRF_TOKEN,loginBean.getCsrfToken());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.LoginSmsToken,loginBean.getLoginSmsToken());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile,loginBean.getUserInfo().getMobile());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord,loginBean.getUserInfo().isHasSafeWord());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin,loginBean.getUserInfo().isLogin());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USER_ID,loginBean.getUserInfo().getId());
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, GsonUtil.GsonString(loginBean.getUserInfo()));
    }


    /**
     * 发送短信验证码
     */
    public void sendRegCode() {
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            showToast(getResources().getString(R.string.phone_empty));
            return;
        }
        DialogUtils.showDialogLoading(this);
        RequestUtils
                .post()
                .url("/api/user/sendFindPwdCode")
                .addParams("mobile",phone)
                .build()
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new CommonCallBack() {


                    @Override
                    protected void onError(String errorMsg) {
                        showToast(errorMsg);
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    protected void onSuccess(String dataJson) {
                        TimerUtils.getInitialise().startTimer(bt_send, 120, getString(R.string.login_resend_code));
                        DialogUtils.dismissDialogLoading();
                    }

                    @Override
                    public void onCallBackError(Throwable e) {
                        DialogUtils.dismissDialogLoading();
                        showMsg(e);

                    }
                });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((boolean) SharedPreferencesUtils.getInstance().getData("language_state", false)) {
                SharedPreferencesUtils.getInstance().saveData("language_state", false);
                Intent itMain = new Intent(UnbindActivity.this, MainActivity.class);
                startActivity(itMain);
                finish();
                overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
            } else {
                finish();
            }
        }
        return true;
    }

    private void jumpProtocol(String url,String title) {
        baseStartActivityWith("/common/WebPageLoading")
                .withString("url", url)
                .withString("title", title).navigation();
    }
}
